/**
 * @name: findSiblingIds
 * @description: 获取传入id的兄弟节点
 * @param {Array} list //树形机构数据
 * @param {String} id //需要查找的id
 * @return {Array} //返回兄弟节点
 */
function findSiblingIds(list, id) {
  let node;
  for (let i in list) {
    if (list[i].id === id) {
      return list.filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = findSiblingIds(list[i].children, id);
      if (node) return node.filter((v) => v.id !== id);
    }
  }
  return node;
}

function addStationName(list) {
  list.forEach((item) => {
    if (item.level == 1) {
      item.label = item.orgName;
      item.id = item.orgId;
    }
    if (item.level == 2) {
      item.label = item.stationName;
      item.id = item.stationId;
    }
    if (item.level == 3) {
      item.label = item.unitsName;
      item.id = item.unitsId;
    }

    if (item.children) {
      addStationName(item.children);
    }
  });
  return list;
}

// 传入一个id获取它父级的id
function getAllParentNodes(list, id) {
  if (list.length === 0 || !list) return [];
  let node;

  for (let i in list) {
    if (list[i].id === id) {
      return [list[i]].filter((v) => v.id !== id);
    }
    if (list[i].children?.length > 0) {
      node = getAllParentNodes(list[i].children, id);
      if (node) return node.concat(list[i]).filter((v) => v.id !== id);
    }
  }
  return node;
}

import { Message } from "element-ui";
import {
  queryStationFileList,
  updateStationInfoFile,
  queryStationTestNumber,
} from "@/api/windPower.js";
import {
  adjustRegulationList,
  regulationOrgList,
  stationTypeList,
  voltageLevelList,
  queryUnitsNameList,
  queryStationNameList,
  queryOfExperimentalresults,
  updateStationFileWarn,
} from "@/api/dict.js";
import TestResultEdit from "@/views/testResult/testResultEdit/testResultEdit.vue";
import ConfigurationRevisionEdit from "@/views/ConfigurationRevision/edit/index.vue";
import { queryTableList } from "@/api/UsageAnalysis.js";
import { queryPlansData } from "@/api/common.js";
import { queryDetailTableList } from "@/api/configurationCheck.js";

export default {
  components: { TestResultEdit, ConfigurationRevisionEdit },
  name: "LabProjectIndex",
  data() {
    return {
      queryStationFileList,
      queryStationNameList,
      queryUnitsNameList,
      queryTableList,
      formData: new FormData(),
      excelData: [],
      columns: [],
      getFrom: {}, //每行的数据
      dispatchList: [], //调度
      stationTypeLists: [], //类型
      adjustRegulationLists: [], //上下调投入分类下拉框的数据
      voltageLevelLists: [], //电压等级下拉框的数据
      addDialogVisibleTitle: "新增",
      id: 0,
      dataTree: [],
      currentLivingId: "",
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],

      defaultProps: {
        children: "list",
        label: "name",
      },
      queryDetailParam: {
        planId: "",
        page: {
          pageIndex: 1,
          pageSize: 10,
        },
      },
      operate: "add",
      testNumberList: [], //测试序号
      isYes: [
        {
          label: "是",
          value: 1,
        },
        {
          label: "否",
          value: 0,
        },
      ],
      headList: [
        {
          name: "规划节点",
          value: "planningName",
          noSort: true,
        },
        {
          name: "规划功率(kW)",
          value: "stationName",
          noSort: true,
        },
        {
          name: "规划容量(kWh)",
          value: "regulationOrgName",
          noSort: true,
        },
        {
          name: "规划功率修正值(kW)",
          value: "stationName",
          type: "editInput",
          noSort: true,
        },
        {
          name: "规划容量修正值(kWh)",
          value: "stationName",
          type: "editInput",
          noSort: true,
        },
      ],
      tableData: [],
      // 新增弹框显示
      dialogFormVisible: false,
      formLabelWidth: "80px",
      // 预览弹框f
      dialogPreVisible: false,
      paramData: [],
      checkList: [],
      checkId: "",
      queryParamStationId: "",
      showXLSX: false,
      xData: [
        "4.1",
        "4.2",
        "4.3",
        "4.4",
        "4.5",
        "4.6",
        "4.7",
        "4.8",
        "4.9",
        "4.10",
        "4.11",
        "4.12",
      ],
      // 弹框数据
      dialogTitle: "",
      dialogVisible: false,
      diglogFormData: {
        planningNode: "",
        ratedCapacity: "",
        ratedPower: "",
      },
      listInfo: {
        pageTotal: 2, // 总条数
        pageSizes: [5, 10, 20, 50, 100], // 分页数量列表
        query: {
          // 查询条件
          current: 1, // 当前页
          size: 10, // 每页条数
        },
      },
      total: 2,
      filterText: "",
      currentPlanId: "",
      // 树节点相关
      allIds: [],
      defaultExpandedNode: [],
      currentKey: "",
    };
  },

  mounted() {
    this.getTreeFn();
  },
  created() {
    // this.regulationOrgList()
    // this.stationTypeList()
    // this.adjustRegulationList()
    // this.voltageLevelList()
    // this.getTreeData()
    // this.queryStationTestNumber()
  },
  watch: {
    filterText(val) {
      this.$refs.equipmentTree.filter(val);
    },
  },
  methods: {
    cellClickFn(row, column, cell, event) {
      console.log("column.property", column.property);
      // console.log("column", row[column.property]);
      if (column.property == "xz") {
        this.$set(row, "isSetXz", true);
      }
      if (column.property == "xzz") {
        this.$set(row, "isSetXzz", true);
      }
    },
    // 编辑
    editFn() {
      this.dialogTitle = "经济最优规划3-1";
      this.dialogVisible = true;
      this.diglogFormData = Object.assign(
        {},
        {
          planningNode: "shanghai",
          ratedCapacity: "",
          ratedPower: "",
        }
      );
    },
    // 获取渲染树的数据
    getTreeData(data) {},
    // 下拉框change事件
    inputChange(val) {
      // console.log(val, "搜索下拉框val");
      // console.log(this.$refs.equipmentTree.queryInputListCopy, "搜索下拉框val");
      let param = {
        stationId: val,
      };
      this.getTreeData(param);
    },
    // 点击树的勾选框
    handleCheck(checkedKeys, e) {
      if (this.queryParamStationId !== "") {
        console.log("有查询条件");
        let params = {
          regulationOrgIds: [],
          stationIds: [],
          fileSort: "01",
        };

        if (e.checkedKeys[1]) {
          params.stationIds.push(e.checkedKeys[1]);
        }
        this.queryDetailParam = params;
      } else {
        console.log("无查询条件");
        let nodeList = this.$refs.equipmentTree.getCheckedNodes();
        let params = {
          regulationOrgIds: [],
          stationIds: [],
          fileSort: "01",
        };
        nodeList
          .filter((e) => e.level !== "3")
          .forEach((item) => {
            if (item.level === "1") {
              params.regulationOrgIds.push(item.id);
            }
            if (item.level === "2") {
              params.stationIds.push(item.id);
            }
          });
        this.queryDetailParam = params;
        params.stationIds.forEach((e, i) => {
          if (
            params.regulationOrgIds.includes(
              getAllParentNodes(this.dataTree, e)[0].id
            )
          ) {
            // 找到这个元素删掉他
            this.queryDetailParam.stationIds =
              this.queryDetailParam.stationIds.filter((d) => d !== e);
          }
        });
      }
      this.$nextTick(() => {
        this.$refs.windPowerTable.getDataInit();
      });
    },
    // 处理三级节点之间勾选联动
    checkChange(row, col, check) {
      //console.log(this.dataTree, "this.dataTree");
      if (row.level == "3") {
        // console.log(row, col, check, "row, col");
        let checkedKeys = findSiblingIds(this.dataTree, row.id);
        // console.log(checkedKeys,'checkedKeyscheckedKeys')
        checkedKeys.forEach((item) => {
          this.$refs.equipmentTree.setChecked(item.id, col);
        });
      }
    },

    // 总调下拉框的数据
    async regulationOrgList() {
      await regulationOrgList().then((res) => {
        if (res.code === "000000") {
          this.dispatchList = res.data;
        }
      });
    },

    // 上下调投入分类下拉框的数据
    async adjustRegulationList() {
      await adjustRegulationList().then((res) => {
        if (res.code === "000000") {
          this.adjustRegulationLists = res.data;
        }
      });
    },
    // 场站类型下拉框的数据
    async stationTypeList() {
      await stationTypeList().then((res) => {
        if (res.code === "000000") {
          this.stationTypeLists = res.data;
        }
      });
    },
    // 电压等级下拉框的数据
    async voltageLevelList() {
      await voltageLevelList().then((res) => {
        if (res.code === "000000") {
          this.voltageLevelLists = res.data;
        }
      });
    },

    // 测试序号下拉
    async queryStationTestNumber() {
      await queryStationTestNumber(this.queryDetailParam).then((res) => {
        if (res.code === "000000") {
          this.testNumberList = res.data;
        }
      });
    },

    // 测试日期
    testDateChange(val) {
      if (val) {
        this.$set(this.queryDetailParam, "testNumber", "");
        this.queryStationTestNumber();
      }
    },
    // 新增弹框
    addWindPower() {
      this.id++;
      // this.operate === "add";
      this.$set(this, "operate", "add");
      this.dialogFormVisible = true;
      this.addDialogVisibleTitle = "新增";
      this.getFrom = { regulationOrgId: "1", caseIsAudited: "" };
      console.log(this.getFrom);
    },

    // 获取表格多行选中的数据  点击行选中
    getMultipleSelection2(row) {
      this.tableData = JSON.parse(JSON.stringify(row));
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    getMultipleSelection() {
      this.tableData = JSON.parse(
        JSON.stringify(this.$refs.windPowerTable.multipleSelection)
      );
      this.tableData.forEach((element) => {
        this.getFrom = element;
      });
    },

    // 编辑
    editWindPower(row) {
      console.log(row);
      if (row) {
        this.$set(this, "operate", "edit");
        this.getMultipleSelection2([row]);
        this.dialogFormVisible = true;
        this.addDialogVisibleTitle = "修正";
        return true;
      } else {
        this.operate = "edit";
        this.getMultipleSelection();
        if (this.tableData && this.tableData.length < 1) {
          Message.warning("请先勾选要编辑的数据");
        } else if (this.tableData && this.tableData.length > 1) {
          Message.warning("编辑的时候只能选择一条数据,请重新选择");
          return false;
        } else {
          this.addDialogVisibleTitle = "修正";
          this.dialogFormVisible = true;
          // this.$nextTick(()=>{
          // this.$refs.childRules.$refs.stationRefEdit.value=this.getFrom.stationName
          // })
          return true;
        }
      }
    },

    // 检索
    searchList() {
      this.$refs.windPowerTable.getDataInit();
    },

    handleClear() {
      this.getTreeData();
    },

    // 给树节点添加唯一标识
    dataTreeFn(data) {
      for (const item of data) {
        if (item.list) {
          item.id = item.name;
          this.dataTreeFn(item.list);
        } else {
          item.id = item.id;
          this.allIds.push(item.id);
        }
      }
    },

    // 获取树结构
    async getTreeFn() {
      let params = {
        regulationOrgIds: [],
        stationIds: [],
        fileSort: "01",
        testDate: "",
        testNumber: "",
        isAudited: 1,
      };
      let { resultCode, data } = await queryPlansData(params);
      if (resultCode == 0) {
        this.dataTree = data;
        this.dataTreeFn(data);
        this.currentKey = this.allIds[0];

        if (this.currentKey) {
          // 默认展开第一条
          this.defaultExpandedNode.push(this.currentKey);
          this.queryDetailParam.planId = this.currentKey;
          this.expandDefault();
          this.handleNodeClick({ id: this.currentKey });
        }
      }
    },

    // 默认展开第一条
    expandDefault() {
      if (this.currentKey) {
        this.$nextTick(() => {
          this.$refs.equipmentTree.setCurrentKey(this.currentKey);
        });
      }
    },
    // 树搜索
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },

    // 单击节点
    handleNodeClick(data) {
      console.log(data);
      if (!data.hasOwnProperty("list")) {
        this.currentPlanId = data.id;
        this.getTableList();
      }
    },

    async getTableList() {
      let params = {
        planId: this.currentPlanId,
        page: {
          pageIndex: 1,
          pageSize: 10,
        },
      };
      let res = await queryDetailTableList(params);
      if (res.resultCode == 0) {
        this.tableData = [];
        res.data.forEach((el) => {
          this.tableData.push({
            nodeId: el.nodeId,
            ratedP: el.ratedP,
            capacity: el.capacity,
            xz: "",
            xzz: "",
          });
        });
      }
    },
    // // pageSize 改变时会触发
    // handleSizeChange(val) {
    //   const query = this.listInfo.query;
    //   query.size = val; // 每页条数
    //   query.current = 1; // 每页条数切换，重置当前页
    //   // this.getData(this.api);
    // },
    // // currentPage 改变时会触发
    // handleCurrentChange(val) {
    //   this.listInfo.query.current = val; // 当前页
    //   // this.getData(this.api);
    // },
  },
};
